Ccay.UI.Repeat = {};
(function(Repeat){

	// set defalut config
	var config = {
		ajax : null,
		tmpl : null,
		showPager: true,
		pagerTarget: null,
		pagerOp: {
			pageInf: {
				pageSize: Ccay.UI.Config.pager.defaultSize,
				curPage: 1
			}
		},
		startIndex: 0
	};
	
	var factory = Repeat.Factory = {
		//初始化分页控件
	   initPager:function(repeat, op){
	   		var pager;
			if (!op.pagerTarget) {
				var id = repeat.id + '_pager';
				$.create('div', null, id).insertAfter(repeat.dom);
				op.pagerTarget = '#' + id;
			}
			pager = repeat.getPager();
			var fnChanged = op.pagerOp.fnPageChanged;
	       	op.pagerOp.fnPageChanged = function (pageInf) {
	       		if(!fnChanged || fnChanged(pageInf) !== false) {
	       			op.pagerOp.pageInf = pageInf;
	       			repeat.request();
	       		}
	       	}
			pager.pager(op.pagerOp);
			op.handler.afterBindData.add(function (repeat, op) {
   				repeat.getPager().pager(op.pagerOp);
			});
		}
	};
	
	//define control flow
	var flow = {
		preInit: function (repeat, op) {
			
		},
		init: function (repeat, op) {
		
		},
		build: function (repeat, op) {
			
		},
		bindEvent: function (repeat, op) {
		
		},
		initComplete:function(repeat,op){
			op.showPager && op.pagerTarget && factory.initPager(repeat, op);
		},
		initAjax:function (repeat, op, ajax){
			var fnSetAjax = ajax.setAjax;
	       	ajax.setAjax = function(ajax){
	       		if((!fnSetAjax || fnSetAjax(ajax) !== false) && ajax.url)
	       		{
		       		ajax.url = ajax.url.formatText(op.pagerOp.pageInf.pageSize, op.pagerOp.pageInf.curPage); 
	       		}
	       	};
	       	ajax.error = function(){
	       		
		    };
		},
		preBindData: function (repeat, op, data, pageVO) {
			pageVO && (op.pagerOp.pageInf = pageVO);
			var pageInf = op.pagerOp.pageInf;
            op.startIndex = (pageInf.curPage -1) * pageInf.pageSize + 1;
            //设置总记录数
           	pageInf.totalRows == 0 && op.dataset && op.dataset.length && (pageInf.totalRows = op.dataset.length);
		},
		bindData:function(repeat, op, data){
			repeat.dom.ccayTemplate(op, data);
		},
		bindDataComplete:function(repeat, op){
			
		},
		complete:function(repeat,op){
		
		}
	};
	//define control manager
	var manager = {
		//overwrite base
		//get dom object 
		getPager: function(){
			var pager = this.op.pagerTarget;
			return pager ? $(pager) : null;
		},
		//get object
		//operate funciton
		reload: function (pagerInf) {
			var pager = this.getPager();
			if(pager.length){
				pager.manager().changePage(pagerInf);
			}
		}
	};
	
	//define inner functions
	var helper = {};
	
	//create XControl
	var XRepeat = Ccay.UI.XControl("XRepeat", flow, config, manager,"Table");
	
	//custom  && handler
	
	// create jquery plugin
	$.fn.repeat = function(op){
		return new XRepeat (this, op);
	}
	
})(Ccay.UI.Repeat);